// 游戏配置
const config = {
    canvasWidth: 640,
    canvasHeight: 480,
    gridSize: 20,
    tankSpeed: 2,
    bulletSpeed: 5,
    bulletCooldown: 300, // 毫秒
    enemySpawnRate: 2000, // 毫秒
    enemySpeed: 1,
    powerupRate: 5000, // 毫秒
    playerHealth: 3
};

// 游戏状态
const gameState = {
    isRunning: false,
    isPaused: false,
    score: 0,
    level: 1,
    lives: config.playerHealth,
    lastEnemySpawn: 0,
    lastPowerupSpawn: 0,
    enemyCount: 0,
    keys: {
        ArrowUp: false,
        ArrowDown: false,
        ArrowLeft: false,
        ArrowRight: false,
        ' ': false // 使用空格字符而不是'Space'
    },
    mobile: {
        isMoving: false,
        direction: { x: 0, y: 0 }
    },
    isTouchFiring: false // 新增：触摸射击状态
};

// 游戏对象
const gameObjects = {
    player: null,
    enemies: [],
    bullets: [],
    walls: [],
    powerups: [],
    explosions: []
};

// DOM 元素
const elements = {
    canvas: null,
    ctx: null,
    scoreDisplay: null,
    livesDisplay: null,
    levelDisplay: null,
    startBtn: null,
    pauseBtn: null,
    restartBtn: null,
    gameOverModal: null,
    levelCompleteModal: null,
    finalScoreDisplay: null,
    finalLevelDisplay: null,
    playAgainBtn: null,
    nextLevelBtn: null,
    joystick: null,
    joystickInner: null,
    fireBtn: null
};

// 方向常量
const Direction = {
    UP: 0,
    RIGHT: 1,
    DOWN: 2,
    LEFT: 3
};

// 初始化游戏
function initGame() {
    // 获取DOM元素
    elements.canvas = document.getElementById('gameCanvas');
    elements.ctx = elements.canvas.getContext('2d');
    elements.scoreDisplay = document.getElementById('score');
    elements.livesDisplay = document.getElementById('lives');
    elements.levelDisplay = document.getElementById('level');
    elements.startBtn = document.getElementById('startBtn');
    elements.pauseBtn = document.getElementById('pauseBtn');
    elements.restartBtn = document.getElementById('restartBtn');
    elements.gameOverModal = document.getElementById('gameOver');
    elements.levelCompleteModal = document.getElementById('levelComplete');
    elements.finalScoreDisplay = document.getElementById('finalScore');
    elements.finalLevelDisplay = document.getElementById('finalLevel');
    elements.playAgainBtn = document.getElementById('playAgainBtn');
    elements.nextLevelBtn = document.getElementById('nextLevelBtn');
    elements.joystick = document.getElementById('joystick');
    elements.joystickInner = document.querySelector('.joystick-inner');
    elements.fireBtn = document.getElementById('fireBtn');
    
    // 设置画布尺寸
    elements.canvas.width = config.canvasWidth;
    elements.canvas.height = config.canvasHeight;
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 初始化游戏地图
    initMap();
}

// 绑定事件监听器
function bindEventListeners() {
    // 键盘控制
    window.addEventListener('keydown', (e) => {
        if (e.key in gameState.keys) {
            gameState.keys[e.key] = true;
        }
    });
    
    window.addEventListener('keyup', (e) => {
        if (e.key in gameState.keys) {
            gameState.keys[e.key] = false;
        }
    });
    
    // 按钮控制
    elements.startBtn.addEventListener('click', startGame);
    elements.pauseBtn.addEventListener('click', togglePause);
    elements.restartBtn.addEventListener('click', restartGame);
    elements.playAgainBtn.addEventListener('click', restartGame);
    elements.nextLevelBtn.addEventListener('click', nextLevel);
    
    // 移动设备控制
    setupMobileControls();
}

// 设置移动设备控制
function setupMobileControls() {
    const joystickRect = elements.joystick.getBoundingClientRect();
    const joystickCenter = {
        x: joystickRect.width / 2,
        y: joystickRect.height / 2
    };
    const joystickRadius = joystickRect.width / 2;
    const innerRadius = elements.joystickInner.offsetWidth / 2;
    
    // 触摸事件
    elements.joystick.addEventListener('touchstart', (e) => {
        e.preventDefault();
        gameState.mobile.isMoving = true;
        updateJoystick(e.touches[0]);
    });
    
    elements.joystick.addEventListener('touchmove', (e) => {
        e.preventDefault();
        if (gameState.mobile.isMoving) {
            updateJoystick(e.touches[0]);
        }
    });
    
    elements.joystick.addEventListener('touchend', (e) => {
        e.preventDefault();
        gameState.mobile.isMoving = false;
        gameState.mobile.direction = { x: 0, y: 0 };
        elements.joystickInner.style.transform = 'translate(0, 0)';
    });
    
    // 触摸射击控制优化
    let lastTouchFire = 0;
    
    // 触摸开始事件
    elements.fireBtn.addEventListener('touchstart', (e) => {
        e.preventDefault();
        gameState.isTouchFiring = true;
        touchFire();
    });
    
    // 触摸移动事件（在按钮上移动也能射击）
    elements.fireBtn.addEventListener('touchmove', (e) => {
        e.preventDefault();
        if (gameState.isTouchFiring) {
            touchFire();
        }
    });
    
    // 触摸结束事件
    elements.fireBtn.addEventListener('touchend', (e) => {
        e.preventDefault();
        gameState.isTouchFiring = false;
    });
    
    // 触摸离开按钮事件
    elements.fireBtn.addEventListener('touchleave', (e) => {
        e.preventDefault();
        gameState.isTouchFiring = false;
    });
    
    function touchFire() {
        const currentTime = Date.now();
        if (gameState.isRunning && !gameState.isPaused && gameObjects.player && 
            currentTime - lastTouchFire > config.bulletCooldown) {
            fireBullet(gameObjects.player);
            lastTouchFire = currentTime;
        }
    }
    
    function updateJoystick(touch) {
        const rect = elements.joystick.getBoundingClientRect();
        const x = touch.clientX - rect.left - joystickCenter.x;
        const y = touch.clientY - rect.top - joystickCenter.y;
        const distance = Math.sqrt(x * x + y * y);
        
        if (distance > joystickRadius - innerRadius) {
            const scale = (joystickRadius - innerRadius) / distance;
            gameState.mobile.direction.x = x * scale / (joystickRadius - innerRadius);
            gameState.mobile.direction.y = y * scale / (joystickRadius - innerRadius);
            elements.joystickInner.style.transform = `translate(${x * scale}px, ${y * scale}px)`;
        } else {
            gameState.mobile.direction.x = x / (joystickRadius - innerRadius);
            gameState.mobile.direction.y = y / (joystickRadius - innerRadius);
            elements.joystickInner.style.transform = `translate(${x}px, ${y}px)`;
        }
    }
}

// 初始化地图
function initMap() {
    gameObjects.walls = [];
    
    // 创建边界墙
    for (let x = 0; x <= config.canvasWidth; x += config.gridSize) {
        gameObjects.walls.push({
            x: x,
            y: 0,
            width: config.gridSize,
            height: config.gridSize,
            isDestructible: false
        });
        gameObjects.walls.push({
            x: x,
            y: config.canvasHeight - config.gridSize,
            width: config.gridSize,
            height: config.gridSize,
            isDestructible: false
        });
    }
    
    for (let y = config.gridSize; y < config.canvasHeight - config.gridSize; y += config.gridSize) {
        gameObjects.walls.push({
            x: 0,
            y: y,
            width: config.gridSize,
            height: config.gridSize,
            isDestructible: false
        });
        gameObjects.walls.push({
            x: config.canvasWidth - config.gridSize,
            y: y,
            width: config.gridSize,
            height: config.gridSize,
            isDestructible: false
        });
    }
    
    // 创建随机墙体
    const wallCount = 30;
    for (let i = 0; i < wallCount; i++) {
        let placed = false;
        while (!placed) {
            const x = Math.floor(Math.random() * (config.canvasWidth / config.gridSize - 2)) * config.gridSize + config.gridSize;
            const y = Math.floor(Math.random() * (config.canvasHeight / config.gridSize - 2)) * config.gridSize + config.gridSize;
            
            // 确保不覆盖玩家出生点
            if (Math.abs(x - config.canvasWidth / 2) < config.gridSize * 3 && Math.abs(y - config.canvasHeight / 2) < config.gridSize * 3) {
                continue;
            }
            
            // 检查是否与其他墙体重叠
            let overlaps = false;
            for (const wall of gameObjects.walls) {
                if (x === wall.x && y === wall.y) {
                    overlaps = true;
                    break;
                }
            }
            
            if (!overlaps) {
                gameObjects.walls.push({
                    x: x,
                    y: y,
                    width: config.gridSize,
                    height: config.gridSize,
                    isDestructible: true
                });
                placed = true;
            }
        }
    }
}

// 开始游戏
function startGame() {
    if (gameState.isRunning) return;
    
    gameState.isRunning = true;
    gameState.isPaused = false;
    gameState.lastEnemySpawn = Date.now();
    gameState.lastPowerupSpawn = Date.now();
    
    // 初始化玩家坦克
    gameObjects.player = {
        x: config.canvasWidth / 2 - config.gridSize / 2,
        y: config.canvasHeight / 2 - config.gridSize / 2,
        width: config.gridSize,
        height: config.gridSize,
        direction: Direction.UP,
        speed: config.tankSpeed,
        lastFired: 0,
        isInvulnerable: false,
        invulnerabilityTimer: 0
    };
    
    // 清空其他对象
    gameObjects.enemies = [];
    gameObjects.bullets = [];
    gameObjects.powerups = [];
    gameObjects.explosions = [];
    
    // 更新显示
    updateDisplay();
    
    // 开始游戏循环
    gameLoop();
}

// 游戏循环
function gameLoop() {
    if (!gameState.isRunning || gameState.isPaused) return;
    
    const currentTime = Date.now();
    
    // 清空画布
    elements.ctx.fillStyle = '#111';
    elements.ctx.fillRect(0, 0, config.canvasWidth, config.canvasHeight);
    
    // 更新玩家
    updatePlayer(currentTime);
    
    // 生成敌人
    if (currentTime - gameState.lastEnemySpawn > config.enemySpawnRate / gameState.level) {
        spawnEnemy();
        gameState.lastEnemySpawn = currentTime;
    }
    
    // 生成道具
    if (currentTime - gameState.lastPowerupSpawn > config.powerupRate) {
        spawnPowerup();
        gameState.lastPowerupSpawn = currentTime;
    }
    
    // 更新敌人
    updateEnemies();
    
    // 更新子弹
    updateBullets();
    
    // 更新道具
    updatePowerups();
    
    // 更新爆炸效果
    updateExplosions();
    
    // 绘制所有对象
    drawAllObjects();
    
    // 检查游戏状态
    checkGameState();
    
    // 继续游戏循环
    requestAnimationFrame(gameLoop);
}

// 更新玩家
function updatePlayer(currentTime) {
    if (!gameObjects.player) return;
    
    const player = gameObjects.player;
    
    // 处理键盘控制
    let moveX = 0;
    let moveY = 0;
    
    if (gameState.keys.ArrowUp) {
        moveY = -player.speed;
        player.direction = Direction.UP;
    }
    if (gameState.keys.ArrowDown) {
        moveY = player.speed;
        player.direction = Direction.DOWN;
    }
    if (gameState.keys.ArrowLeft) {
        moveX = -player.speed;
        player.direction = Direction.LEFT;
    }
    if (gameState.keys.ArrowRight) {
        moveX = player.speed;
        player.direction = Direction.RIGHT;
    }
    
    // 处理移动设备控制
    if (gameState.mobile.isMoving) {
        const threshold = 0.3;
        
        if (Math.abs(gameState.mobile.direction.y) > Math.abs(gameState.mobile.direction.x)) {
            if (gameState.mobile.direction.y < -threshold) {
                moveY = -player.speed;
                player.direction = Direction.UP;
            } else if (gameState.mobile.direction.y > threshold) {
                moveY = player.speed;
                player.direction = Direction.DOWN;
            }
        } else {
            if (gameState.mobile.direction.x < -threshold) {
                moveX = -player.speed;
                player.direction = Direction.LEFT;
            } else if (gameState.mobile.direction.x > threshold) {
                moveX = player.speed;
                player.direction = Direction.RIGHT;
            }
        }
    }
    
    // 处理射击 - 优化键盘控制，支持按住空格持续射击
    if (gameState.keys[' '] && currentTime - player.lastFired > config.bulletCooldown) {
        fireBullet(player);
        player.lastFired = currentTime;
    }
    
    // 处理移动和碰撞
    if (moveX !== 0 || moveY !== 0) {
        const newX = player.x + moveX;
        const newY = player.y + moveY;
        
        // 检查与墙体的碰撞
        if (!checkCollision(newX, newY, player.width, player.height, gameObjects.walls)) {
            // 检查与敌人的碰撞
            const enemyCollision = checkCollision(newX, newY, player.width, player.height, gameObjects.enemies);
            if (!enemyCollision) {
                player.x = newX;
                player.y = newY;
            } else if (!player.isInvulnerable) {
                // 与敌人碰撞，扣除生命值
                takeDamage();
            }
        }
    }
    
    // 更新无敌状态
    if (player.isInvulnerable) {
        player.invulnerabilityTimer--;
        if (player.invulnerabilityTimer <= 0) {
            player.isInvulnerable = false;
        }
    }
}

// 生成敌人
function spawnEnemy() {
    const sides = [
        { x: config.gridSize * 2, y: config.gridSize * 2, direction: Direction.RIGHT }, // 左上角
        { x: config.canvasWidth - config.gridSize * 3, y: config.gridSize * 2, direction: Direction.LEFT }, // 右上角
        { x: config.gridSize * 2, y: config.canvasHeight - config.gridSize * 3, direction: Direction.RIGHT }, // 左下角
        { x: config.canvasWidth - config.gridSize * 3, y: config.canvasHeight - config.gridSize * 3, direction: Direction.LEFT } // 右下角
    ];
    
    const randomSide = sides[Math.floor(Math.random() * sides.length)];
    
    // 确保不会在玩家附近生成敌人
    if (gameObjects.player) {
        const playerDistance = Math.sqrt(
            Math.pow(randomSide.x - gameObjects.player.x, 2) +
            Math.pow(randomSide.y - gameObjects.player.y, 2)
        );
        
        if (playerDistance < config.gridSize * 5) {
            return;
        }
    }
    
    gameObjects.enemies.push({
        x: randomSide.x,
        y: randomSide.y,
        width: config.gridSize,
        height: config.gridSize,
        direction: randomSide.direction,
        speed: config.enemySpeed + (gameState.level - 1) * 0.2,
        lastDirectionChange: Date.now(),
        fireCooldown: 2000 - (gameState.level - 1) * 100,
        lastFired: Date.now()
    });
    
    gameState.enemyCount++;
}

// 更新敌人
function updateEnemies() {
    const currentTime = Date.now();
    
    for (let i = gameObjects.enemies.length - 1; i >= 0; i--) {
        const enemy = gameObjects.enemies[i];
        
        // 随机改变方向
        if (currentTime - enemy.lastDirectionChange > 2000 + Math.random() * 2000) {
            enemy.direction = Math.floor(Math.random() * 4);
            enemy.lastDirectionChange = currentTime;
        }
        
        // 尝试向玩家方向移动
        if (gameObjects.player && Math.random() < 0.2) {
            const dx = gameObjects.player.x - enemy.x;
            const dy = gameObjects.player.y - enemy.y;
            
            if (Math.abs(dx) > Math.abs(dy)) {
                enemy.direction = dx > 0 ? Direction.RIGHT : Direction.LEFT;
            } else {
                enemy.direction = dy > 0 ? Direction.DOWN : Direction.UP;
            }
        }
        
        // 计算移动
        let moveX = 0;
        let moveY = 0;
        
        switch (enemy.direction) {
            case Direction.UP:
                moveY = -enemy.speed;
                break;
            case Direction.RIGHT:
                moveX = enemy.speed;
                break;
            case Direction.DOWN:
                moveY = enemy.speed;
                break;
            case Direction.LEFT:
                moveX = -enemy.speed;
                break;
        }
        
        // 尝试移动
        const newX = enemy.x + moveX;
        const newY = enemy.y + moveY;
        
        if (!checkCollision(newX, newY, enemy.width, enemy.height, gameObjects.walls)) {
            enemy.x = newX;
            enemy.y = newY;
        } else {
            // 如果碰撞，随机改变方向
            enemy.direction = Math.floor(Math.random() * 4);
        }
        
        // 敌人射击
        if (currentTime - enemy.lastFired > enemy.fireCooldown && Math.random() < 0.02) {
            fireBullet(enemy);
            enemy.lastFired = currentTime;
        }
    }
}

// 发射子弹
function fireBullet(tank) {
    let bulletX, bulletY;
    
    // 根据坦克方向设置子弹初始位置
    switch (tank.direction) {
        case Direction.UP:
            bulletX = tank.x + tank.width / 2 - 2;
            bulletY = tank.y - 10;
            break;
        case Direction.RIGHT:
            bulletX = tank.x + tank.width;
            bulletY = tank.y + tank.height / 2 - 2;
            break;
        case Direction.DOWN:
            bulletX = tank.x + tank.width / 2 - 2;
            bulletY = tank.y + tank.height;
            break;
        case Direction.LEFT:
            bulletX = tank.x - 10;
            bulletY = tank.y + tank.height / 2 - 2;
            break;
    }
    
    // 确定子弹所有者（玩家或敌人）
    const owner = tank === gameObjects.player ? 'player' : 'enemy';
    
    gameObjects.bullets.push({
        x: bulletX,
        y: bulletY,
        width: 4,
        height: 4,
        direction: tank.direction,
        speed: config.bulletSpeed,
        owner: owner
    });
}

// 更新子弹
function updateBullets() {
    for (let i = gameObjects.bullets.length - 1; i >= 0; i--) {
        const bullet = gameObjects.bullets[i];
        
        // 移动子弹
        switch (bullet.direction) {
            case Direction.UP:
                bullet.y -= bullet.speed;
                break;
            case Direction.RIGHT:
                bullet.x += bullet.speed;
                break;
            case Direction.DOWN:
                bullet.y += bullet.speed;
                break;
            case Direction.LEFT:
                bullet.x -= bullet.speed;
                break;
        }
        
        // 检查子弹是否超出画布
        if (bullet.x < 0 || bullet.x > config.canvasWidth || bullet.y < 0 || bullet.y > config.canvasHeight) {
            gameObjects.bullets.splice(i, 1);
            continue;
        }
        
        // 检查与墙体的碰撞
        const wallHit = checkCollision(bullet.x, bullet.y, bullet.width, bullet.height, gameObjects.walls);
        if (wallHit && wallHit.isDestructible) {
            // 创建爆炸效果
            createExplosion(bullet.x, bullet.y);
            
            // 移除墙体
            const wallIndex = gameObjects.walls.indexOf(wallHit);
            if (wallIndex !== -1) {
                gameObjects.walls.splice(wallIndex, 1);
            }
            
            // 移除子弹
            gameObjects.bullets.splice(i, 1);
            continue;
        } else if (wallHit && !wallHit.isDestructible) {
            // 创建爆炸效果
            createExplosion(bullet.x, bullet.y);
            
            // 移除子弹
            gameObjects.bullets.splice(i, 1);
            continue;
        }
        
        // 检查与坦克的碰撞
        if (bullet.owner === 'player') {
            // 玩家子弹击中敌人
            for (let j = gameObjects.enemies.length - 1; j >= 0; j--) {
                const enemy = gameObjects.enemies[j];
                if (checkCollision(bullet.x, bullet.y, bullet.width, bullet.height, [enemy])) {
                    // 创建爆炸效果
                    createExplosion(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
                    
                    // 移除敌人
                    gameObjects.enemies.splice(j, 1);
                    gameState.enemyCount--;
                    
                    // 增加分数
                    gameState.score += 100;
                    updateDisplay();
                    
                    // 移除子弹
                    gameObjects.bullets.splice(i, 1);
                    break;
                }
            }
        } else {
            // 敌人子弹击中玩家
            if (gameObjects.player && !gameObjects.player.isInvulnerable && 
                checkCollision(bullet.x, bullet.y, bullet.width, bullet.height, [gameObjects.player])) {
                // 创建爆炸效果
                createExplosion(bullet.x, bullet.y);
                
                // 玩家受伤
                takeDamage();
                
                // 移除子弹
                gameObjects.bullets.splice(i, 1);
            }
        }
    }
}

// 生成道具
function spawnPowerup() {
    const powerupTypes = ['health', 'rapidFire', 'invulnerability'];
    const type = powerupTypes[Math.floor(Math.random() * powerupTypes.length)];
    
    // 随机位置，避开边界和玩家出生点
    let x, y;
    let validPosition = false;
    
    while (!validPosition) {
        x = Math.floor(Math.random() * (config.canvasWidth / config.gridSize - 4)) * config.gridSize + config.gridSize * 2;
        y = Math.floor(Math.random() * (config.canvasHeight / config.gridSize - 4)) * config.gridSize + config.gridSize * 2;
        
        // 确保不会在墙体上生成
        let onWall = false;
        for (const wall of gameObjects.walls) {
            if (x >= wall.x - config.gridSize && x <= wall.x + config.gridSize && 
                y >= wall.y - config.gridSize && y <= wall.y + config.gridSize) {
                onWall = true;
                break;
            }
        }
        
        if (!onWall) {
            validPosition = true;
        }
    }
    
    gameObjects.powerups.push({
        x: x,
        y: y,
        width: config.gridSize - 4,
        height: config.gridSize - 4,
        type: type,
        timer: 600 // 约10秒（60帧/秒）
    });
}

// 更新道具
function updatePowerups() {
    for (let i = gameObjects.powerups.length - 1; i >= 0; i--) {
        const powerup = gameObjects.powerups[i];
        
        // 减少计时器
        powerup.timer--;
        if (powerup.timer <= 0) {
            gameObjects.powerups.splice(i, 1);
            continue;
        }
        
        // 检查与玩家的碰撞
        if (gameObjects.player && checkCollision(
            powerup.x, powerup.y, powerup.width, powerup.height, [gameObjects.player])) {
            
            // 应用道具效果
            applyPowerup(powerup.type);
            
            // 移除道具
            gameObjects.powerups.splice(i, 1);
        }
    }
}

// 应用道具效果
function applyPowerup(type) {
    switch (type) {
        case 'health':
            if (gameState.lives < config.playerHealth) {
                gameState.lives++;
                updateDisplay();
            }
            break;
        case 'rapidFire':
            // 临时提高射速
            const originalCooldown = config.bulletCooldown;
            config.bulletCooldown = 150;
            
            setTimeout(() => {
                config.bulletCooldown = originalCooldown;
            }, 10000);
            break;
        case 'invulnerability':
            // 临时无敌
            if (gameObjects.player) {
                gameObjects.player.isInvulnerable = true;
                gameObjects.player.invulnerabilityTimer = 600; // 约10秒
            }
            break;
    }
}

// 创建爆炸效果
function createExplosion(x, y) {
    gameObjects.explosions.push({
        x: x,
        y: y,
        radius: 5,
        maxRadius: 20,
        alpha: 1,
        speed: 1
    });
}

// 更新爆炸效果
function updateExplosions() {
    for (let i = gameObjects.explosions.length - 1; i >= 0; i--) {
        const explosion = gameObjects.explosions[i];
        
        // 扩大爆炸半径
        explosion.radius += explosion.speed;
        
        // 降低透明度
        explosion.alpha -= 0.05;
        
        // 移除完成的爆炸效果
        if (explosion.alpha <= 0) {
            gameObjects.explosions.splice(i, 1);
        }
    }
}

// 检查碰撞
function checkCollision(x, y, width, height, objects) {
    for (const obj of objects) {
        if (
            x < obj.x + obj.width &&
            x + width > obj.x &&
            y < obj.y + obj.height &&
            y + height > obj.y
        ) {
            return obj;
        }
    }
    return null;
}

// 玩家受伤
function takeDamage() {
    gameState.lives--;
    updateDisplay();
    
    if (gameObjects.player) {
        // 给玩家短暂无敌时间
        gameObjects.player.isInvulnerable = true;
        gameObjects.player.invulnerabilityTimer = 180; // 约3秒
    }
    
    // 检查游戏是否结束
    if (gameState.lives <= 0) {
        gameOver();
    }
}

// 检查游戏状态
function checkGameState() {
    // 检查关卡是否完成（消灭所有敌人）
    if (gameState.enemyCount === 0 && gameObjects.enemies.length === 0) {
        levelComplete();
    }
}

// 关卡完成
function levelComplete() {
    gameState.isPaused = true;
    gameState.level++;
    
    // 更新显示
    updateDisplay();
    
    // 显示关卡完成弹窗
    elements.levelCompleteModal.style.display = 'flex';
}

// 进入下一关
function nextLevel() {
    elements.levelCompleteModal.style.display = 'none';
    
    // 重新初始化地图
    initMap();
    
    // 清空敌人和子弹
    gameObjects.enemies = [];
    gameObjects.bullets = [];
    
    // 继续游戏
    gameState.isPaused = false;
    gameLoop();
}

// 游戏结束
function gameOver() {
    gameState.isRunning = false;
    
    // 更新最终得分和关卡
    elements.finalScoreDisplay.textContent = gameState.score;
    elements.finalLevelDisplay.textContent = gameState.level;
    
    // 显示游戏结束弹窗
    elements.gameOverModal.style.display = 'flex';
}

// 暂停/继续游戏
function togglePause() {
    if (!gameState.isRunning) return;
    
    gameState.isPaused = !gameState.isPaused;
    
    if (!gameState.isPaused) {
        gameLoop();
    }
}

// 重新开始游戏
function restartGame() {
    // 重置游戏状态
    gameState.score = 0;
    gameState.level = 1;
    gameState.lives = config.playerHealth;
    
    // 隐藏弹窗
    elements.gameOverModal.style.display = 'none';
    elements.levelCompleteModal.style.display = 'none';
    
    // 重新初始化地图
    initMap();
    
    // 开始游戏
    startGame();
}

// 更新显示
function updateDisplay() {
    elements.scoreDisplay.textContent = gameState.score;
    elements.livesDisplay.textContent = gameState.lives;
    elements.levelDisplay.textContent = gameState.level;
}

// 绘制所有对象
function drawAllObjects() {
    // 绘制墙体
    for (const wall of gameObjects.walls) {
        elements.ctx.fillStyle = wall.isDestructible ? '#666' : '#333';
        elements.ctx.fillRect(wall.x, wall.y, wall.width, wall.height);
        
        // 绘制边框
        elements.ctx.strokeStyle = '#999';
        elements.ctx.strokeRect(wall.x, wall.y, wall.width, wall.height);
    }
    
    // 绘制玩家坦克
    if (gameObjects.player) {
        const player = gameObjects.player;
        
        // 如果无敌，闪烁效果
        if (player.isInvulnerable && Math.floor(Date.now() / 100) % 2 === 0) {
            return;
        }
        
        elements.ctx.save();
        
        // 移动到坦克中心并旋转
        elements.ctx.translate(player.x + player.width / 2, player.y + player.height / 2);
        elements.ctx.rotate((player.direction * 90) * Math.PI / 180);
        
        // 绘制坦克车身
        elements.ctx.fillStyle = '#00ff00';
        elements.ctx.fillRect(-player.width / 2, -player.height / 2, player.width, player.height);
        
        // 绘制坦克炮管
        elements.ctx.fillStyle = '#00cc00';
        elements.ctx.fillRect(-2, -player.height / 2 - 5, 4, 10);
        
        elements.ctx.restore();
    }
    
    // 绘制敌人坦克
    for (const enemy of gameObjects.enemies) {
        elements.ctx.save();
        
        // 移动到坦克中心并旋转
        elements.ctx.translate(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
        elements.ctx.rotate((enemy.direction * 90) * Math.PI / 180);
        
        // 绘制坦克车身
        elements.ctx.fillStyle = '#ff3333';
        elements.ctx.fillRect(-enemy.width / 2, -enemy.height / 2, enemy.width, enemy.height);
        
        // 绘制坦克炮管
        elements.ctx.fillStyle = '#cc0000';
        elements.ctx.fillRect(-2, -enemy.height / 2 - 5, 4, 10);
        
        elements.ctx.restore();
    }
    
    // 绘制子弹
    for (const bullet of gameObjects.bullets) {
        elements.ctx.fillStyle = bullet.owner === 'player' ? '#00ff00' : '#ff3333';
        elements.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
    }
    
    // 绘制道具
    for (const powerup of gameObjects.powerups) {
        elements.ctx.save();
        
        // 根据道具类型设置颜色
        switch (powerup.type) {
            case 'health':
                elements.ctx.fillStyle = '#ff3333';
                break;
            case 'rapidFire':
                elements.ctx.fillStyle = '#3333ff';
                break;
            case 'invulnerability':
                elements.ctx.fillStyle = '#ffff33';
                break;
        }
        
        // 绘制闪烁效果
        if (Math.floor(powerup.timer / 30) % 2 === 0) {
            elements.ctx.globalAlpha = 0.7;
        }
        
        // 绘制道具
        elements.ctx.beginPath();
        elements.ctx.arc(
            powerup.x + powerup.width / 2,
            powerup.y + powerup.height / 2,
            powerup.width / 2,
            0,
            Math.PI * 2
        );
        elements.ctx.fill();
        
        elements.ctx.restore();
    }
    
    // 绘制爆炸效果
    for (const explosion of gameObjects.explosions) {
        elements.ctx.save();
        elements.ctx.globalAlpha = explosion.alpha;
        
        // 绘制爆炸外圈
        elements.ctx.beginPath();
        elements.ctx.arc(explosion.x, explosion.y, explosion.radius, 0, Math.PI * 2);
        elements.ctx.fillStyle = 'rgba(255, 165, 0, 0.7)';
        elements.ctx.fill();
        
        // 绘制爆炸内圈
        elements.ctx.beginPath();
        elements.ctx.arc(
            explosion.x,
            explosion.y,
            explosion.radius * 0.6,
            0,
            Math.PI * 2
        );
        elements.ctx.fillStyle = 'rgba(255, 255, 0, 0.7)';
        elements.ctx.fill();
        
        elements.ctx.restore();
    }
}

// 当页面加载完成后初始化游戏
window.addEventListener('load', initGame);